package org.PropertyManageMentSystem.Manager;

import org.PropertyManageMentSystem.Data.MysqlConfig;

import java.sql.*;

public class OwnerManager {
    private Connection conn;
    public OwnerManager(MysqlConfig config) throws SQLException, ClassNotFoundException {
        try {
            //加载驱动
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

        try {
            //创建连接
            conn = DriverManager.getConnection(config.getUrl(), config.getUser(), config.getPassword());
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    private Long findDirectorId() throws SQLException {
        String sql="select * from director";
        PreparedStatement pst=conn.prepareStatement(sql);
        ResultSet rs = pst.executeQuery();
        rs.next();
        return rs.getLong("directorId");
    }

    public Long addOwner(String ownerName, String ownerTel, String ownerAddress) throws Exception {
        Long ownerId = findOwner(ownerName, ownerTel);
        if (ownerId == null) {
            String regex = "[1][34578][0-9]{9}";
            if (!ownerTel.matches(regex)) {
                throw new Exception("电话号码格式错误");
            }
            else {
                long directorId = findDirectorId();

                String sql = "insert into owner (ownerName, ownerTel, ownerAddress, directorId) values(?,?,?,?)";
                PreparedStatement pst = conn.prepareStatement(sql);

                pst.setString(1, ownerName);
                pst.setString(2, ownerTel);
                pst.setString(3, ownerAddress);
                pst.setLong(4, directorId);

                pst.executeUpdate();
                pst.close();

                ownerId = findOwner(ownerName, ownerTel);
            }
        }
        return ownerId;
    }

    private Long findOwner(String ownerName, String ownerTel) throws SQLException {
        String sql="select * from owner where ownerName=? and ownerTel=?";
        PreparedStatement pst=conn.prepareStatement(sql);
        pst.setString(1, ownerName);
        pst.setString(2, ownerTel);
        ResultSet rs = pst.executeQuery();
        if (rs.next()) {
            return rs.getLong("ownerId");
        }
        else {
            return null;
        }
    }
    public Long findOwnerByName(String ownerName) throws SQLException {
        String sql="select * from owner where ownerName=?";
        PreparedStatement pst=conn.prepareStatement(sql);
        pst.setString(1, ownerName);
        ResultSet rs = pst.executeQuery();
        if (rs.next()) {
            return rs.getLong("ownerId");
        }
        else {
            return null;
        }
    }

}
